#!/usr/local/bin/php

<?php
  require_once('daemons.conf.php');
  require_once('lib/ses.php');
  require_once("lib/db.broker.php");
  require_once("lib/create-daemon.php");

  $db = New broker;

  while (true) {

    if ($signal_code) {
      exit;
    }

    if ($handle = opendir(SYNCRO_FOLDER)) {
      while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

          if ($signal_code) {
            exit;
          }

          if (strstr($entry, 'sends_tries_')) {
            $tries_info = get_tries_info($entry);
            $id = $tries_info['id'];
            // update tries
            $update_sql = "UPDATE `sends` SET `tries` = (`tries`+1) WHERE (`id` = {$id})";
            $res = $db->update($update_sql);
            if ($res) unlink(SYNCRO_FOLDER.$entry);
          }
          
          if (strstr($entry, 'sends_sent_')) {
            $sent_info = get_sent_info($entry);
            $awsmessageid = $sent_info['MessageId'];
            $id = $sent_info['id'];
            // update sends
            $update_sql = "UPDATE `sends` SET `sent` = NOW(), `awsmessageid` = '{$awsmessageid}' WHERE (`id` = {$id})";
            $res = $db->update($update_sql);
            if ($res) unlink(SYNCRO_FOLDER.$entry);
          }

        }
      }
      closedir($handle);

      if ($signal_code) {
        exit;
      }

    }
    sleep(5); // dejamos descanzar al procesador

    if ($signal_code) {
      exit;
    }

  }


  function get_tries_info($filename) {
    $res = explode("_", $filename);    

    return array(
      'id' => $res[2]
    );
  }

  function get_sent_info($filename) {
    $res = explode("_", $filename);    

    return array(
      'id'        => $res[2],
      'MessageId' => $res[3]
    );
  }
